﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITAP.ShprossesBuilder.Modelling.Components;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using ITAP.ShprossesBuilder.Utils;
using ITAP.Core.Utils;

namespace ITAP.ShprossesBuilder.Operations {
    public class OperationLoadZippedModel : IOperation {
        private byte[] zippedBytes;
        public OperationLoadZippedModel(byte[] zippedBytes) {
            this.zippedBytes = zippedBytes;
        }
        #region IOperation Members

        public string Name {
            get {
                return "Загрузка сжатой модели из массива байт";
            }
        }

        public OperationGroup OperationGroup {
            get {
                return OperationGroup.Other;
            }
        }

        public System.Drawing.Image Thumbnail {
            get {
                return null;
            }
        }

        public void Execute(ModelControl modelControl) {
            ModelCell cell = new ModelCell();          
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            stream.Write(zippedBytes, 0, zippedBytes.Length);
            MemoryStream unzippedStream = new MemoryStream();
            stream.Seek(0, SeekOrigin.Begin);
            Archiver.UnZip(stream, unzippedStream);
            object _model = formatter.Deserialize(unzippedStream);
            Model model = _model as Model;
            stream.Close();
            unzippedStream.Close();
            cell.AddInnerComponent(model);
            ModelCellRepository cellRepository = new ModelCellRepository();
            cellRepository.AddCell(cell, 0, 0);
            modelControl.ModelContainer = new ModelContainer();
            modelControl.ModelContainer.Initialize(cellRepository);
        }

        public bool CanUndo {
            get {
                return false;
            }
        }

        #endregion
    }
}
